import React, { Component } from 'react';
import { View } from 'react-native';
import RefreshListView from "../Refresh/RefreshListView";
import { queryFuli } from '../common/Service';
import FuliCell from "../widgets/FuliCell";
import RefreshState from "../Refresh/RefreshState";

export default class FuliListScreen extends Component {

  constructor(props) {
    super(props);
    this.nextPage = 1;
    this.state = {
      dataList: [],  // 电影列表的数据源
    };
  }

  componentDidMount() {
    this.listView.beginHeaderRefresh();
  }

  render() {
    return (
      <RefreshListView
        numColumns={3}
        ref={(ref) => { this.listView = ref }}
        data={this.state.dataList}
        renderItem={this._renderItem}
        keyExtractor={(item) => item._id}
        ListEmptyComponent={this._renderEmptyView}
        onHeaderRefresh={() => {
          console.log("onHeaderRefresh");
          this.nextPage = 1;
          this.loadData()
        }}
        onFooterRefresh={() => {
          console.log("onFooterRefresh");
          this.loadData()
        }}
      />
    )
  }

  _renderItem = (data) => {
    let item = data.item;
    return (
      <FuliCell item={item} onPress={() => {
        console.log('点击了Item----' + item.title);
      }} />
    )
  };

  /// 渲染一个空白页，当列表无数据的时候显示。这里简单写成一个View控件
  _renderEmptyView = (item) => {
    return <View />
  };

  /**
   * 加载正在上映的电影列表，此处默认城市为北京，取20条数据显示
   */
  loadData() {
    console.log("loadData nextPage = " + this.nextPage);
    let that = this;
    fetch(queryFuli(this.nextPage)).then((response) => response.json()).then((json) => {
      console.log(json);
      let results = json.results;
      let footerState = RefreshState.Idle;
      // if (this.nextPage == 2) {//测试: 底部全部加载
      //   results = [];
      // }
      if (results && results.length > 0) {
        // results = results.slice(1);//测试：单数加载
        let dataList = this.nextPage > 1 ? this.state.dataList.concat(results) : results;
        that.setState({
          dataList: dataList,//测试：如果这里设置为results，则如果loading more后设置到列表的数据比之前的数据少或相等，就会导致频繁调用onReachEnd，最后导致频繁onFooterRefresh
        });
        this.nextPage++;
        footerState = RefreshState.CanLoadMore;
      } else {
        footerState = RefreshState.NoMoreData;
      }
      that.listView.endRefreshing(footerState);
    }).catch((e) => {
      console.log("加载失败");
      console.log(e);
      that.listView.endRefreshing(RefreshState.Failure);
    }).done();
  }
}